package com.teradata.olingo.plugin;

import com.teradata.olingo.service.ApiKeysService;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

@Component
@ConditionalOnBean(ApiKeysService.class)
public class SynGetPrimitiveFromDbPlugin {


    @Autowired
    ApiKeysService apiKeysService;


    @Autowired
    JdbcTemplate jdbcTemplate;



    public class EntityRowMapper implements RowMapper {

        private String entitySetName;

        private List<EdmKeyPropertyRef> keyPropertyRefs;

        public EntityRowMapper(){}

        public EntityRowMapper(String entitySetName, List<EdmKeyPropertyRef> keyPropertyRefs) {
            this.entitySetName = entitySetName;
            this.keyPropertyRefs = keyPropertyRefs;
        }

        @Nullable
        @Override
        public Property mapRow(ResultSet rs, int rowNum) throws SQLException {

            Property property = new Property();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String key = rsmd.getColumnLabel(i);
                Object value = rs.getObject(i);

                property = new Property(null, key, ValueType.PRIMITIVE, value);

            }
            //createId(entitySetName, property, keyPropertyRefs);
            return property;
        }


    }


    public Property getPrimitiveByJdbcTemplate(String sql, String entitySetName, List<EdmKeyPropertyRef> keyPropertyRefs){

        Property property = (Property) jdbcTemplate.queryForObject(
                sql, new Object[] {}, new EntityRowMapper(entitySetName, keyPropertyRefs));

        return property;
    }



    /*private void createId(String entitySetName, Property property, List<EdmKeyPropertyRef> keyPropertyRefs) {
        try {

            ArrayList<String> propStrList = new ArrayList<>();

            for (EdmKeyPropertyRef keyPropertyRef : keyPropertyRefs) {
                propStrList.add(keyPropertyRef.getName() + "=" + property.getValue());
            }

            String keyStr = Joiner.on(",").join(propStrList);

            entity.setId(new URI(entitySetName + OlingoUtil.mkString(keyStr,"(",")")));
        } catch (URISyntaxException e) {
            throw new ODataRuntimeException("Unable to create id for entity: " + entitySetName, e);
        }
    }*/
}
